<template>
  <div>
    <button @click="sendTestMessage">发送测试消息</button>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">
        {{ msg.content }} @ {{ msg.timestamp }}
      </li>
    </ul>
  </div>
</template>

<script>
import Stomp from 'stompjs'; // 确保安装了 stompjs: npm install stompjs

export default {
  data() {
    return {
      messages: [],
      stompClient: null, // 初始化 stompClient
    };
  },
  mounted() {
    this.connectWebSocket();
  },
  methods: {
    connectWebSocket() {
      const socket = new WebSocket('ws://localhost:8888/ws'); // 替换为你的 WebSocket URL
      this.stompClient = Stomp.over(socket);

      // 设置 debug 为 null 以禁用默认的日志输出
      this.stompClient.debug = null;

      this.stompClient.connect(
          {}, // 连接头信息
          (frame) => {
            console.log('Connected:', frame);
            this.stompClient.subscribe('/topic/notifications', (message) => {
              this.messages.push(JSON.parse(message.body));
            });
          },
          (error) => {
            console.error('WebSocket connection error:', error);
          }
      );
    },
    sendTestMessage() {
      fetch('http://localhost:8888/api/send', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content: 'Hello from Vue!',
          timestamp: new Date().toISOString(),
        }),
      })
          .then((response) => {
            if (response.ok) {
              console.log('Test message sent successfully');
            } else {
              console.error('Failed to send test message');
            }
          })
          .catch((error) => {
            console.error('Error sending test message:', error);
          });
    },
  },
};
</script>